//当前日期时间
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
//当前日期
const Time = date => {
  date.setDate(date.getDate() + 1)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return `${[year, month, day].map(formatNumber).join('-')}`
}
//当前日期的前一个月
const Yearime = date => {
  const year = date.getFullYear()
  const month = date.getMonth()
  const day = date.getDate() - 2

  return `${[year, month, day].map(formatNumber).join('-')}`
}

//时间字符串转换为时间戳
const dateTime = date => {
  date = date.substring(0, 19);
  date = date.replace(/-/g, '/');
  const timestamp = new Date(date).getTime();
  return timestamp
}

const dateAddDays = date => {
  var isdate = new Date(date.replace(/-/g, "/")); //把日期字符串转换成日期格式

  isdate.setDate(isdate.getDate() + 1)
  const year = isdate.getFullYear()
  const month = isdate.getMonth() + 3 //增加两个月的时间
  const day = isdate.getDate()
  return `${[year, month, day].map(formatNumber).join('-')}`
}

//历史记录 计算总时长
function formatTimeTwo(mss) {
  var hours = parseInt(mss / 60 / 60);
  var minutes = parseInt(mss / 60 % 60);
  var seconds = (mss % 60);
  return hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 ";
}

// const formatNumber = n => {
//   n = n.toString()
//   return n[1] ? n : `0${n}`
// }

/**  
 * 格式化数字显示方式   
 * 用法  
 * formatNumber(12345.999,'#,##0.00');  
 * formatNumber(12345.999,'#,##0.##');  
 * formatNumber(123,'000000');
 */
function formatNumber(v, pattern) {
  if (v == null)
    return v;
  var strarr = v ? v.toString().split('.') : ['0'];
  var fmtarr = pattern ? pattern.split('.') : [''];
  var retstr = '';
  // 整数部分   
  var str = strarr[0];
  var fmt = fmtarr[0];
  var i = str.length - 1;
  var comma = false;
  for (var f = fmt.length - 1; f >= 0; f--) {
    switch (fmt.substr(f, 1)) {
      case '#':
        if (i >= 0) retstr = str.substr(i--, 1) + retstr;
        break;
      case '0':
        if (i >= 0) retstr = str.substr(i--, 1) + retstr;
        else retstr = '0' + retstr;
        break;
      case ',':
        comma = true;
        retstr = ',' + retstr;
        break;
    }
  }
  if (i >= 0) {
    if (comma) {
      var l = str.length;
      for (; i >= 0; i--) {
        retstr = str.substr(i, 1) + retstr;
        if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
      }
    } else retstr = str.substr(0, i + 1) + retstr;
  }
  retstr = retstr + '.';
  // 处理小数部分   
  str = strarr.length > 1 ? strarr[1] : '';
  fmt = fmtarr.length > 1 ? fmtarr[1] : '';
  i = 0;
  for (var f = 0; f < fmt.length; f++) {
    switch (fmt.substr(f, 1)) {
      case '#':
        if (i < str.length) retstr += str.substr(i++, 1);
        break;
      case '0':
        if (i < str.length) retstr += str.substr(i++, 1);
        else retstr += '0';
        break;
    }
  }
  return retstr.replace(/^,+/, '').replace(/\.$/, '');
};

/**
 * 格式化时间显示方式
 * 用法:format="yyyy-MM-dd hh:mm:ss";
 */
function formatDate(v, format) {
  if (!v) return "";
  var d = v;
  if (typeof v === 'string') {
    if (v.indexOf("/Date(") > -1)
      d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
    else
      d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[
      0])); //.split(".")[0] 用来处理出现毫秒的情况，截取掉.xxx，否则会出错
  }
  var o = {
    "M+": d.getMonth() + 1, //month
    "d+": d.getDate(), //day
    "h+": d.getHours(), //hour
    "m+": d.getMinutes(), //minute
    "s+": d.getSeconds(), //second
    "q+": Math.floor((d.getMonth() + 3) / 3), //quarter
    "S": d.getMilliseconds() //millisecond
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;

function out_of_china(lng, lat) {
  return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
}

function transformlat(lng, lat) {
  var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
  ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
  ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
  return ret
}

function transformlng(lng, lat) {
  var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
  ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
  ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
  return ret

}

function wgs84togcj02(lng, lat) {
  if (out_of_china(lng, lat)) {
    return [lng, lat]
  } else {
    var dlat = transformlat(lng - 105.0, lat - 35.0);
    var dlng = transformlng(lng - 105.0, lat - 35.0);
    var radlat = lat / 180.0 * PI;
    var magic = Math.sin(radlat);
    magic = 1 - ee * magic * magic;
    var sqrtmagic = Math.sqrt(magic);
    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
    dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
    var mglat = lat + dlat;
    var mglng = lng + dlng;
    return [mglng, mglat]
  }
}

/** * json格式转树状结构 * @param   {json}      json数据 * @param   {String}    id的字符串 * @param   {String}    父id的字符串 * @param   {String}    children的字符串 * @return  {Array}     数组 */function toTreeData(a, idStr, pidStr, childrenStr) {    var r = [], hash = {}, len = (a || []).length;    for (var i = 0; i < len; i++) {        hash[a[i][idStr]] = a[i];    }    for (var j = 0; j < len; j++) {        var aVal = a[j], hashVP = hash[aVal[pidStr]];        if (hashVP) {            !hashVP[childrenStr] && (hashVP[childrenStr] = []);            hashVP[childrenStr].push(aVal);        } else {            r.push(aVal);        }    }    return r;};

module.exports = {
  formatTime,
  Time,
  Yearime,
  dateTime,
  dateAddDays,
  formatTimeTwo: formatTimeTwo,
  formatNumber: formatNumber,
  formatDate: formatDate,
  out_of_china: out_of_china,
  transformlat: transformlat,
  transformlng: transformlng,
  wgs84togcj02: wgs84togcj02,
  toTreeData:toTreeData,
}